package com.blobfish.fiction.common.plugin;

import com.blobfish.fiction.common.tio.websocket.ShowcaseServerAioListener;
import com.blobfish.fiction.common.tio.websocket.ShowcaseServerConfig;
import com.blobfish.fiction.common.tio.websocket.ShowcaseWsMsgHandler;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import org.tio.server.ServerGroupContext;
import org.tio.websocket.server.WsServerStarter;

import java.io.IOException;

/**
 * Websocket插件
 * @author huangbo
 */
public class ShowcaseWebsocketPlugin implements IPlugin {
    private static final Log log = Log.getLog(ShowcaseWebsocketPlugin.class);
    private WsServerStarter wsServerStarter;
    public static ServerGroupContext serverGroupContext;

    public ShowcaseWebsocketPlugin(int port, ShowcaseWsMsgHandler wsMsgHandler) throws Exception {
        wsServerStarter = new WsServerStarter(port, wsMsgHandler);

        serverGroupContext = wsServerStarter.getServerGroupContext();
        serverGroupContext.setName(ShowcaseServerConfig.PROTOCOL_NAME);
        serverGroupContext.setServerAioListener(ShowcaseServerAioListener.me);

        // 设置ip监控
        // serverGroupContext.setIpStatListener(ShowcaseIpStatListener.me);
        // 设置ip统计时间段
        serverGroupContext.ipStats.addDurations(ShowcaseServerConfig.IpStatDuration.IPSTAT_DURATIONS);

        // 设置心跳超时时间
        serverGroupContext.setHeartbeatTimeout(ShowcaseServerConfig.HEARTBEAT_TIMEOUT);
    }

    /**
     * @author tanyaowu
     * @throws IOException
     */
    @Override
    public boolean start() {
        try {
            wsServerStarter.start();
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    /**
     * @return the serverGroupContext
     */
    public ServerGroupContext getServerGroupContext() {
        return serverGroupContext;
    }

    public WsServerStarter getWsServerStarter() {
        return wsServerStarter;
    }
}
